import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class ZkServer {

    private ZooKeeper zooKeeper;

    @Before
    public void init() throws IOException {
        zooKeeper = new ZooKeeper("localhost:2181", 1000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.toString());
            }
        });
    }

    @After
    public void close() throws InterruptedException {
        zooKeeper.close();
    }


    public void testCreate() {
        zooKeeper.create("/zks", null, null, CreateMode.PERSISTENT, new AsyncCallback.StringCallback() {
            @Override
            public void processResult(int i, String s, Object o, String s1) {
                System.out.println("创建完毕：" + s);
            }
        }, null);
    }

    public void testChild() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/", true);
        System.out.println(children);
    }

    public void testDelete() throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists("/zks", false);
        System.out.println(stat);
        if (stat != null)
            zooKeeper.delete("/zks", stat.getVersion());
    }

    public void testGet() throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists("/zks", false);
        if (stat != null) {
            // 设置新的值
            zooKeeper.setData("/zks", "hello world".getBytes(), stat.getVersion());
            byte[] data = zooKeeper.getData("/zks", false, stat);
            System.out.println(new String(data));
        }
    }

    @Test
    public void testAuth() throws KeeperException, InterruptedException, IOException {
        //zooKeeper.addAuthInfo("digest", "tong:tong123".getBytes());
        //zooKeeper.create("/zks/node1", "haha".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
        //System.out.println(zooKeeper.getChildren("/zks", null));
        // 创建新的连接
        //System.out.println(new String(zooKeeper.getData("/zks/node1", null, null)));

        ZooKeeper zk = new ZooKeeper("localhost:2181", 5000, null);
        //Stat stat = zk.exists("/zks/node1", false);
        zk.addAuthInfo("digest", "tong:tong123".getBytes());
        System.out.println(new String(zk.getData("/zks/node1", null, null)));
    }

}
